package gerenciaDados.cln.cdp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import javax.swing.JButton;
import javax.swing.table.DefaultTableModel;


public class UDPServer {
	DefaultTableModel l_model;
	volatile boolean Running = true;
	DatagramSocket serverSocket = null;
	private JButton btnContinuar;
	
	private class ServerThread implements Runnable{
		boolean contem(String c, String a, String b){
			for(int i=0;i<l_model.getRowCount();i++){
			String cc = (String)l_model.getValueAt(i,0);
			String aa = (String)l_model.getValueAt(i,1);
			String bb = (String)l_model.getValueAt(i,2);
			if(aa.equals(a) && bb.equals(b) && cc.equals(c)){
				return true;
			}
			}
			
			
			return false;
		}
		public void run(){
			
	         try{
	        	 
	        	 serverSocket = new DatagramSocket(8687);
	         } catch(SocketException e){
	        	 e.printStackTrace();
	         }
	            byte[] receiveData = new byte[1024];
	            byte[] sendData = new byte[1024];
			
			while(getRunning()){
				btnContinuar.setEnabled(l_model.getRowCount() != 0);
				//System.out.println("Rodando");
				try{					
	                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
	                serverSocket.receive(receivePacket);
	                String sentence = new String( receivePacket.getData()).trim();
	                String[] str = sentence.split("-");
	                
	                if(str.length!=3){
	                	continue;
	                }
	                if(!contem(str[0],str[1],str[2])){	                	
	                	Object[] element = {str[0],str[1],str[2]};
	                	l_model.addRow(element);	                	
	                }

				} catch(IOException e){
					System.out.println("Socket UDP Finalizou.");
				}

				
			}
			System.out.println("Saiu!");
			
			
		}
	}
	
	boolean getRunning(){
		return Running;
	}
	public void closeServer(){
		serverSocket.close();
		Running=false;
		
	}
	 public UDPServer(DefaultTableModel l_model, JButton b){
		this.l_model = l_model;
		this.btnContinuar = b;
				
		new Thread(new ServerThread()).start();
	}
}
